
import React, { createContext, useState, useRef, useContext } from "react"
import { getRowColumn } from "@/utils/index";
import { ChatContext } from "./store";
import { sheetConfig } from "@/components/Chat/components/ChatTable/config";

export interface TableContextType {
  coverImgMap: Record<string, any>;
  addTask: (msgId: string, idStr: string, tableData: any, list?: any[]) => void;
  resetImg: () => void;
}

const TableModel = createContext<TableContextType>({
  coverImgMap: {},
  addTask: () => { },
  resetImg: () => { },
})

const TableProvider: React.FC<React.PropsWithChildren> = ({ children }) => {
  const taskRef = useRef<any[]>([])
  const imgRef = useRef<any>({})
  const taskStatus = useRef<boolean>(false)
  const [coverImgMap, setCoverImgMap] = useState<Record<string, any>>({})

  const { updateChatSome } = useContext(ChatContext);

  const runTask = async () => {
    if (taskRef.current.length > 0) {
      taskStatus.current = true
      await taskRef.current[0]()
      taskRef.current.shift()
      if (taskRef.current.length > 0) {
        runTask()
      } else {
        taskStatus.current = false;

        setCoverImgMap({ ...imgRef.current });
        return { ...imgRef.current }
      }
    } else {
      return {}
    }
  }

  const addTask = (msgId: string, idStr: string, tableData: any, list?: any[]) => {
    if (window.luckysheet) {
      const fn = () => {
        return new Promise((reslove, reject) => {
          let newElement = document.createElement('div')
          newElement.style.display = 'none'
          newElement.id = idStr
          document.body.appendChild(newElement);
          const options = {
            ...sheetConfig,
            ...tableData,
            container: idStr,
            hook: {
              workbookCreateAfter: () => {
                const rowColumn = getRowColumn()
                window.luckysheet.setRangeShow(rowColumn);
                const imgUrl = window.luckysheet.getScreenshot()
                imgRef.current[`${idStr}`] = imgUrl;
                updateChatSome(msgId, {
                  tablePreview: imgUrl
                }, list, true)
                newElement.remove();
                reslove(true)
              }
            }
          }
          window.luckysheet.create(options);
        })
      }
      taskRef.current.push(fn)
      if (!taskStatus.current) {
        return runTask()
      }
      return {}
    }
  }
  const resetImg = () => {
    imgRef.current = {}
    setCoverImgMap({})
  }
  return <TableModel.Provider value={{
    coverImgMap,
    addTask,
    resetImg
  }}>
    {children}
  </TableModel.Provider>
}

export default TableModel
export {
  TableProvider,
}


